import number2Duration from './number2Duration.js';
import uuid from './uuid.js';

const countDownObjs = {};

module.exports = function (config = {}) {
	let { 
		id, 
		beginDate, 
		endDate,
		fields = 'day',
		text = '确定',
		aboutToBeginText = '距离开始还有',
		aboutToEndText = '距离结束还有',
		endedText = '已结束',
		intervalTime = 100
	} = config;
	id = id || uuid();
	
	
	const countDownObj = {};
	countDownObj.isStop = false;
	if(countDownObjs[id]) {
		const curObj = countDownObjs[id];
		if(curObj.fn) clearInterval(curObj.fn);
	}
	
	let bgDate;
	if(beginDate) bgDate = +new Date(beginDate);
	
	let edDate;
	if(endDate) edDate = +new Date(endDate);
	
	if(!beginDate && !edDate) {
		setCountDownObj(countDownObj, {}, 3);
		return countDownObj;
	}
	
	handleCountDown(bgDate, edDate, countDownObj, fields);
	
	countDownObj.fn = setInterval(() => {
		handleCountDown(bgDate, edDate, countDownObj, fields);
	}, intervalTime);
	countDownObj.stop = function () { clearInterval(countDownObj.fn); }
	countDownObjs[id] = countDownObj;
	return countDownObj;
}

function getNumber2Duration (d, fields) {
	return number2Duration(d, 'detail', fields);
}

function handleCountDown(bgDate, edDate, countDownObj, fields) {
	const nNow = +new Date();
	
	if(bgDate && !edDate) {
		if (nNow < bgDate) {
			setCountDownObj(countDownObj, getNumber2Duration(bgDate - nNow, fields), 1);
		}else{
			setCountDownObj(countDownObj, {}, 2);
			stopCountDown(countDownObj);
		}
	}else if(!bgDate && edDate) {
		if (nNow < edDate) {
			setCountDownObj(countDownObj, getNumber2Duration(edDate - nNow, fields), 2);
		}else{
			setCountDownObj(countDownObj, {}, 3);
			stopCountDown(countDownObj);
		}
	}else{
		if (nNow < bgDate) {
			setCountDownObj(countDownObj, getNumber2Duration(bgDate - nNow, fields), 1);
		} else if (nNow >= bgDate && nNow < edDate) {
			setCountDownObj(countDownObj, getNumber2Duration(edDate - nNow, fields), 2);
		} else {
			setCountDownObj(countDownObj, {}, 3);
			stopCountDown(countDownObj);
		}
	}
}

function stopCountDown(c) {
	if(c.stop && typeof c.stop == 'function') {
		c.stop();
	}else{
		clearInterval(c.fn);
	}
	c.fn = null;
	c.isStop = true;
}

function setCountDownObj (obj, detail = {}, status) {
	obj.text = detail.text;
	obj.day = detail.day ?? '00';
	obj.hour = detail.hour ?? '00';
	obj.minute = detail.minute ?? '00';
	obj.second = detail.second ?? '00';
	obj.status = status;
}